import pandas as pd

# 计算移动平均
moving_averages = {
    '5': 5,
    '10': 10,
    '20': 20,
    '30': 30,
    '60': 60,
    '120': 120
}


def calculate_moving_avg(df,_max_num = 120):
    # 计算每个时间段的移动平均值
    for period, window in moving_averages.items():
        df[f'MA{period}'] = df['close'].rolling(window=window).mean()
        df[f'MA{period}_lag'] = df[f'MA{period}'].shift(window)
        df[f'MA{period}_slope'] = (((df[f'MA{period}'] - df[f'MA{period}_lag']) / df[f'MA{period}_lag']) * 100) / window
        df[f'MA{period}_max'] = df[f'MA{period}_slope'].rolling(window=_max_num).max()
        df[f'MA{period}_min'] = df[f'MA{period}_slope'].rolling(window=_max_num).min()
    return df


if __name__=="__main__":
    from stock_base_daily import get_daily_file
    import matplotlib.pyplot as plt
    import math
    df = get_daily_file('600732',tail_num= 1000)
    _df = calculate_moving_avg(df)
    # 计算5日前的5日均线
    _df['MA5_lag'] = _df['MA5'].shift(5)
    # 计算每日5日均线的变化率
    _df['MA5_slope'] = (((_df['MA5'] - _df['MA5_lag']) / _df['MA5_lag']) * 100)/5

    # 获取最后一条记录的MA5_slope变化率
    last_MA5_slope = df.iloc[-1]['MA5_slope']
    print(f"斜率与水平轴的斜率为: {last_MA5_slope:.2f}")
    # 计算斜率与水平轴的角度
    # 将斜率变化率转换为弧度
    slope_radians = math.atan(abs(last_MA5_slope / 100))
    # 将角度转换为与水平轴的夹角
    angle_with_horizontal_axis = slope_radians - math.pi / 2

    # 将弧度转换为度数
    angle_degrees = math.degrees(angle_with_horizontal_axis)

    print(f"斜率与水平轴的角度为: {angle_degrees:.2f}°")
    # 绘制斜率图
    plt.figure(figsize=(10, 5))
    plt.plot(_df['date'], _df['MA5_slope'], marker='o')
    plt.title('5日均线斜率变化')
    plt.xlabel('交易日')
    plt.ylabel('斜率 (%)')
    plt.grid(True)
    plt.show()